package com.frank.player;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;

import com.frank.player.listener.OnErrorListener;
import com.frank.player.listener.OnPreparedListener;
import com.frank.player.media.AudioPlayer;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private AudioPlayer mAudioPlayer;
    private String mAudioUrl = new File(Environment.getExternalStorageDirectory(), "input.mp3").getAbsolutePath();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        verifyStoragePermissions();
        AppCompatButton mPlayAudioBtn = findViewById(R.id.btn_play_audio);

        mAudioPlayer = new AudioPlayer();

        mAudioPlayer.setDataSource(mAudioUrl);
        mAudioPlayer.setOnErrorListener(new OnErrorListener() {
            @Override
            public void onError(int code, String msg) {
                Log.e("AudioPlayer", "onError: " + msg);
            }
        });

        mAudioPlayer.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared() {
                Log.e("AudioPlayer", "onPrepared: ");
                mAudioPlayer.play();
            }
        });
        mPlayAudioBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mAudioPlayer.prepareAsync();
            }
        });
    }

    public void verifyStoragePermissions() {
        int permission = ActivityCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }
}
